import { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

/**根据窗口大小resize动态改变图形 
 * @param option 图表配置项
 * @param deps 图表依赖项, 当依赖项变化时, 会重新渲染图表
 * @returns 图表实例
 * @example   const chartRef = useEchartsResize(option, [])
*/
const useEchartsResize = (option: any, deps: any[]) => {
  const chartRef = useRef(null);

  useEffect(() => {
    let chart: any = null;
    if (chartRef.current) {
      chart = echarts.init(chartRef.current);
      // 设置初始配置项和数据
      chart.setOption(option);
    }

    const handleResize = () => {
      if (chart) {
        chart.resize();
      }
    };

    window.addEventListener('resize', handleResize);

    return () => {
      if (chart) {
        chart.dispose();
      }
      window.removeEventListener('resize', handleResize);
    };
  }, deps);

  return chartRef;
};

export default useEchartsResize;